package org.os.framework.context.config;

import org.os.framework.context.model.RejectedExecutionHandlers;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务
 * 
 * @author weizuxiao
 */
@Slf4j
@Data
@ConfigurationProperties(prefix = "spring.scheduling")
@Configuration
@EnableScheduling
public class SchedulingConfig implements SchedulingConfigurer {

    /**
     * 线程池大小
     */
    private Integer poolSize = Runtime.getRuntime().availableProcessors() * 2;

    /**
     * 线程池名称前置
     */
    private String threadNamePrefix = "scheduled-pool-";

    /**
     * 是否等待所有任务完成后再关闭线程池
     */
    private Boolean waitForJobsToCompleteOnShutdown = true;

    /**
     * 关闭时等待所有任务完成的最长时间（秒）
     */
    private Integer awaitTerminationSeconds = 60;

    /**
     * 拒绝策略
     */
    private RejectedExecutionHandlers rejectedExecutionHandler = RejectedExecutionHandlers.Abort;

    @Override
    public void configureTasks(@NonNull ScheduledTaskRegistrar scheduledTaskRegistrar) {
        log.info("已启用定时任务配置：{}", this);
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(poolSize);
        scheduler.setThreadNamePrefix(threadNamePrefix);
        scheduler.setRejectedExecutionHandler(rejectedExecutionHandler.getRejectedExecutionHandler());
        scheduler.setWaitForTasksToCompleteOnShutdown(waitForJobsToCompleteOnShutdown);
        scheduler.setAwaitTerminationSeconds(awaitTerminationSeconds);
        scheduler.initialize();
        scheduledTaskRegistrar.setTaskScheduler(scheduler);
    }
}